package com.autonavi.yunda.yunji.core.utils;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author cizhong.wcs
 * @date 2023/12/28 11:35
 */
public class FileUtil {
    public static String parseJarFolderToTempFolder(URL jarUrl, String folderPath) {
        try (JarFile jarFile = ((JarURLConnection) jarUrl.openConnection()).getJarFile()) {
            File tempDirectory = createTempDirectory();
            String destinationFolderPath = tempDirectory.getPath();
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String entryName = entry.getName();
                if (entryName.startsWith(folderPath) && !entry.isDirectory()) {
                    File destinationFile = new File(destinationFolderPath, entryName);
                    File destinationParentDir = destinationFile.getParentFile();
                    if (!destinationParentDir.exists() && !destinationParentDir.mkdirs()) {
                        throw new IOException("Failed to create directory: " + destinationParentDir.getAbsolutePath());
                    }
                    try (InputStream inputStream = jarFile.getInputStream(entry);
                         FileOutputStream outputStream = new FileOutputStream(destinationFile)) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }
                    }
                }
            }
            return tempDirectory.getPath();
        } catch (Exception e) {
            throw new AmapException(AmapExceptionCode.COMMON_SERVER_ERROR, "parseJarFolderToTempFolder error", e);
        }
    }

    public static File createTempDirectory() throws IOException {
        File tempDir;
        try {
            tempDir = File.createTempFile("yunji_temp", Long.toString(System.nanoTime()));
        } catch (IOException e) {
            throw new IOException("Failed to create temporary directory", e);
        }
        if (!tempDir.delete()) {
            throw new IOException("Failed to delete temporary file: " + tempDir.getAbsolutePath());
        }
        if (!tempDir.mkdir()) {
            throw new IOException("Failed to create temporary directory: " + tempDir.getAbsolutePath());
        }
        return tempDir;
    }

}
